<template>
  <a-modal
    :title="`${ okHidden ? '' : model && model.id ? '编辑' : '新增'}角色`"
    :width="680"
    :visible="visible"
    :confirmLoading="loading"
    @ok="() => { $emit('ok') }"
    @cancel="() => { $emit('cancel') }"
  >
    <a-spin :spinning="loading">
      <a-form :form="form" v-bind="formLayout">
        <a-form-item v-if="model && model.id" label="主键ID" hidden>
          <a-input v-decorator="['id', { initialValue: model.id }]" disabled />
        </a-form-item>
        <a-form-item label="角色名称" v-if="!okHidden">
          <a-input placeholder="请输入角色名称" v-decorator="['name', {rules: [{required: true, message: '角色名称不能为空！' }, {max: 10, message: '最大可输入20个字符！' }]}]" />
        </a-form-item>
        <div v-else>
          <a-form-item label="权限">
            <a-tree-select
              v-decorator="['permission_ids', { rules: [{ required: true, message: '请至少选择一个权限！' }] }]"
              style="width: 100%"
              :tree-data="permissionList"
              tree-checkable
              placeholder="请选择权限"
              :replaceFields="{
                value: 'id',
                title: 'display_name',
                children: 'child_permission'
              }"
            />
          </a-form-item>
        </div>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import pick from 'lodash.pick'
import { TreeSelect } from 'ant-design-vue'
const SHOW_PARENT = TreeSelect.SHOW_PARENT

// 表单字段
const fields = ['permission_ids', 'name']

export default {
  props: {
    visible: {
      type: Boolean,
      required: true
    },
    loading: {
      type: Boolean,
      default: () => false
    },
    okHidden: {
      type: Boolean,
      default: () => false
    },
    model: {
      type: Object,
      default: () => null
    },
    permissionList: {
      type: Array,
      default: () => []
    },
    auth: {
      type: Boolean,
      default: () => false
    }
  },
  data () {
    this.formLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 4 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 19 }
      }
    }
    return {
      form: this.$form.createForm(this),
      currentLength: 0,
      SHOW_PARENT
    }
  },
  created () {
    // 防止表单未注册
    fields.forEach(v => this.form.getFieldDecorator(v))

    // 当 model 发生改变时，为表单设置值
    this.$watch('model', () => {
      this.$nextTick(() => {
        const data = pick(this.model, fields)
        if (this.okHidden) {
          delete data.name
        }
        this.model && this.form.setFieldsValue(data)
      })
    })
  }
}
</script>
